<script setup name="AI4Data">
import { ref, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'

import {
	uploadFileForAnalysis,
	downloadExampleFile,
	getExampleFileContent,
} from '@/api/product/ai4Data'

const { t } = useI18n()

// 响应式数据
const uploadedFile = ref(null)
const pdfPreviewUrl = ref('')
const filePreviewHtml = ref('')
const isInitializing = ref(true)
const isAnalyzing = ref(false)
const isDownloading = ref(false)

// DOM 元素引用
const uploadArea = ref(null)
const fileInput = ref(null)
const analyzeBtn = ref(null)
const pdfPreview = ref(null)
const uploadBtn = ref(null)
const downloadBtn = ref(null)

// 设置默认预览内容
const setDefaultPreview = () => {
	filePreviewHtml.value = `
		<h3 class="preview-title">Data Preview 数据预览</h3>
		<div class="preview-placeholder">
			<div class="placeholder-icon">
				<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M14 2V8H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M16 13H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M16 17H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					<path d="M10 9H9H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
			</div>
			<p class="placeholder-text">上传 CSV 文件以查看数据预览</p>
			<p class="placeholder-hint">支持拖拽上传或点击选择文件</p>
		</div>
	`
}

// 显示 CSV 预览
const displayPreview = (data) => {
	const rows = data.split('\n').slice(0, 10)
	let html =
		'<h3 class="preview-title">Data Preview 数据预览</h3><div class="preview-table-wrapper">'
	html += '<table class="preview-table">'
	rows.forEach((row, index) => {
		const cols = row.split(',')
		html += '<tr>'
		cols.forEach((col) => {
			html += `<td ${index === 0 ? 'class="header-cell"' : ''}>${col.trim()}</td>`
		})
		html += '</tr>'
	})
	html += '</table></div>'
	filePreviewHtml.value = html
}

// 处理文件上传
const handleFile = (file) => {
	if (file && file.type === 'text/csv') {
		uploadedFile.value = file
		const reader = new FileReader()
		reader.onload = (e) => displayPreview(e.target.result)
		reader.readAsText(file)
		analyzeBtn.value.disabled = false
	} else {
		alert('请上传 CSV 文件')
	}
}

// 下载示例文件
const downloadExample = async () => {
	if (isDownloading.value) return

	isDownloading.value = true
	try {
		const blob = await downloadExampleFile('example.csv')
		const link = document.createElement('a')
		link.href = URL.createObjectURL(blob)
		link.download = 'example.csv'
		document.body.appendChild(link)
		link.click()
		setTimeout(() => {
			document.body.removeChild(link)
			URL.revokeObjectURL(link.href)
		}, 100)
	} catch (error) {
		console.error('下载失败:', error)
		alert('下载失败，请检查文件路径')
	} finally {
		isDownloading.value = false
	}
}

// 分析文件
const analyzeFile = async () => {
	if (!uploadedFile.value) {
		alert('请先上传文件')
		return
	}

	if (isAnalyzing.value) return

	isAnalyzing.value = true
	try {
		console.log('开始分析文件:', uploadedFile.value.name)
		const blob = await uploadFileForAnalysis(uploadedFile.value)
		console.log('分析完成，blob size:', blob.size)

		// 清理之前的URL
		if (pdfPreviewUrl.value) {
			URL.revokeObjectURL(pdfPreviewUrl.value)
		}

		// 创建新的URL
		const newUrl = URL.createObjectURL(blob)
		console.log('新建PDF URL:', newUrl)
		pdfPreviewUrl.value = newUrl

		console.log('PDF URL已设置:', pdfPreviewUrl.value)
		alert('分析完成，PDF 已加载')
	} catch (error) {
		console.error('分析失败:', error)
		alert('上传失败，请稍后重试')
	} finally {
		isAnalyzing.value = false
	}
}

// PDF加载成功回调
const onPdfLoad = () => {
	console.log('PDF加载成功')
}

// PDF加载失败回调
const onPdfError = (error) => {
	console.error('PDF加载失败:', error)
	alert('PDF加载失败，请检查文件格式')
}

// 初始化示例预览
const initExamplePreview = async () => {
	try {
		const data = await getExampleFileContent('example.csv')
		displayPreview(data)
	} catch (error) {
		console.error('Error loading CSV:', error)
		// 如果加载示例失败，显示默认预览
		setDefaultPreview()
	} finally {
		isInitializing.value = false
	}
}

// 修复 UI 问题
const fixUIIssues = () => {
	// 修复图标
	const iconElements = document.querySelectorAll(
		'.achievement-icon-box .icon-circle i'
	)
	const iconClasses = [
		'fa-chart-line',
		'fa-tablet-alt',
		'fa-code',
		'fa-briefcase',
	]

	iconElements.forEach((icon, index) => {
		if (
			getComputedStyle(icon).display === 'none' ||
			!icon.className.includes('fa-')
		) {
			icon.className = 'fa ' + iconClasses[index % iconClasses.length]
		}
	})

	// 调整证书网格
	const certificatesGrid = document.querySelector('.certificates-grid')
	if (certificatesGrid) {
		certificatesGrid.style.display = 'grid'
		certificatesGrid.style.gridTemplateColumns = 'repeat(3, 1fr)'
		certificatesGrid.style.gap = '20px'

		const adjustGrid = () => {
			if (window.innerWidth <= 768) {
				certificatesGrid.style.gridTemplateColumns = 'repeat(2, 1fr)'
			} else if (window.innerWidth <= 576) {
				certificatesGrid.style.gridTemplateColumns = '1fr'
			} else {
				certificatesGrid.style.gridTemplateColumns = 'repeat(3, 1fr)'
			}
		}

		adjustGrid()
		window.addEventListener('resize', adjustGrid)
	}
}

onMounted(() => {
	nextTick(() => {
		// 设置默认预览内容，避免白屏
		setDefaultPreview()

		// 初始化示例数据
		initExamplePreview()

		// 设置拖拽上传
		const uploadAreaEl = uploadArea.value
		uploadAreaEl.addEventListener('dragover', (e) => {
			e.preventDefault()
			uploadAreaEl.classList.add('drag-over')
		})

		uploadAreaEl.addEventListener('dragleave', () => {
			uploadAreaEl.classList.remove('drag-over')
		})

		uploadAreaEl.addEventListener('drop', (e) => {
			e.preventDefault()
			uploadAreaEl.classList.remove('drag-over')
			handleFile(e.dataTransfer.files[0])
		})

		// 设置按钮事件
		uploadBtn.value.addEventListener('click', (e) => {
			e.preventDefault()
			fileInput.value.click()
		})

		downloadBtn.value.addEventListener('click', downloadExample)
		analyzeBtn.value.addEventListener('click', analyzeFile)
		fileInput.value.addEventListener('change', (e) =>
			handleFile(e.target.files[0])
		)

		// 修复UI问题
		fixUIIssues()
	})
})
</script>

<template>
	<main class="ai4data-page">
		<!-- Main Content Section -->
		<section class="hero">
			<!-- Floating particles for dynamic effect -->
			<div class="particles">
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
				<span class="particle"></span>
			</div>

			<!-- Light streaks for horizontal movement effect -->
			<span class="light-streak"></span>
			<span class="light-streak"></span>
			<span class="light-streak"></span>

			<div class="hero-content">
				<h1>{{ t('home.product.dom2.title') }}</h1>
				<p>
					{{ t('home.product.dom2.content') }}
				</p>
			</div>
		</section>
		<section class="main-section">
			<div class="container-plus">
				<div class="content-grid">
					<!-- 左侧上传区域 -->
					<div class="upload-section">
						<div class="upload-container">
							<div ref="uploadArea" class="upload-area">
								<input
									ref="fileInput"
									type="file"
									accept=".csv"
									class="file-input"
								/>
								<div class="upload-icon">
									<svg
										viewBox="0 0 24 24"
										fill="none"
										xmlns="http://www.w3.org/2000/svg"
									>
										<path d="M7 18H17V16H7V18Z" fill="currentColor" />
										<path
											d="M10 14L12 12L14 14H13V17H11V14H10Z"
											fill="currentColor"
										/>
										<path
											d="M12 2L7 7H10V12H14V7H17L12 2Z"
											fill="currentColor"
										/>
									</svg>
								</div>
								<div class="upload-content">
									<p class="upload-text">
										Drag the file here, or<br />
										将文件拖到此处，或
									</p>
									<button ref="uploadBtn" class="upload-btn">
										Click Upload<br />
										点击上传
									</button>
								</div>
							</div>

							<div class="download-section">
								<button
									ref="downloadBtn"
									class="download-btn"
									:class="{ loading: isDownloading }"
									:disabled="isDownloading"
								>
									<div v-if="isDownloading" class="loading-spinner"></div>
									<svg
										v-else
										viewBox="0 0 24 24"
										fill="none"
										xmlns="http://www.w3.org/2000/svg"
									>
										<path
											d="M12 16L7 11H10V4H14V11H17L12 16Z"
											fill="currentColor"
										/>
										<path d="M20 18H4V20H20V18Z" fill="currentColor" />
									</svg>
									<span>
										{{
											isDownloading
												? '下载中...'
												: 'Click Download data sample file (csv format, less than 1G)'
										}}<br />
										{{
											isDownloading
												? '请稍候'
												: '点击下载数据示例文件（csv格式,小于1G）'
										}}
									</span>
								</button>
							</div>

							<div class="file-preview" :class="{ loading: isInitializing }">
								<div v-if="!isInitializing" v-html="filePreviewHtml"></div>
								<div v-else class="loading-container">
									<div class="loading-spinner"></div>
									<p class="loading-text">正在加载示例数据...</p>
								</div>
							</div>

							<div class="analyze-section">
								<button
									ref="analyzeBtn"
									class="analyze-btn"
									:disabled="!uploadedFile || isAnalyzing"
									:class="{ loading: isAnalyzing }"
								>
									<div v-if="isAnalyzing" class="loading-spinner"></div>
									<svg
										v-else
										viewBox="0 0 24 24"
										fill="none"
										xmlns="http://www.w3.org/2000/svg"
									>
										<path
											d="M19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.9 20.1 3 19 3ZM9 17H7V10H9V17ZM13 17H11V7H13V17ZM17 17H15V13H17V17Z"
											fill="currentColor"
										/>
									</svg>
									{{ isAnalyzing ? '数据分析中...' : '开始分析' }}
								</button>
							</div>
						</div>
					</div>

					<!-- 右侧预览区域 -->
					<div class="analysis-section">
						<div class="preview-container">
							<!-- 默认预览图片 -->
							<img
								v-show="!pdfPreviewUrl"
								class="preview-image"
								src="./images/preview2.jpg"
								alt="data preview"
							/>
							<!-- PDF预览 -->
							<iframe
								v-show="pdfPreviewUrl"
								ref="pdfPreview"
								class="pdf-preview"
								:src="pdfPreviewUrl"
								@load="onPdfLoad"
								@error="onPdfError"
							></iframe>
						</div>
					</div>
				</div>
			</div>
		</section>
	</main>
</template>

<style scoped lang="scss">
@import url('@/styles/content/index.scss');
@import url('@/styles/content/product.scss');

.container-plus {
	padding: 0 20px;
}
</style>
